<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsAllot;
use App\Store\Models\Goods\GoodsAllotInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\GoodsAllotService;
use Illuminate\Http\Request;
use App\Store\Validate\Goods\GoodsAllot as ValidateGoodsGoodsAllot;
use Illuminate\Support\Facades\DB;
use App\Store\Services\Goods\Goods;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;

/**
 * 商品调拨
 */
class GoodsAllotController extends Controller
{
    /**
     * 商品调拨单
     * 自己门店【start_store_id】的货，调拨到别的门店【target_store_id】，一对一挑调拨
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['target_store_id', 'goods_list']);
        $Validate = new ValidateGoodsGoodsAllot();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = (int)$accountinfo['store_ids'];
        $target_store_id = (int)$req_data['target_store_id'];

        $storeinfo = SiteStore::where(['id' => $start_store_id, 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        //处理调拨商品列表
        $goods_list = $req_data['goods_list'];
        $goods_list = is_array($goods_list) ? $goods_list : (is_array(json_decode($goods_list, true)) ? json_decode($goods_list, true) : []);

        if (empty($goods_list)) {
            return response()->json(['code' => '001', 'msg' => '调拨数据不能为空']);
        }

        $checkData =(new GoodsAllotService())->checkAllotGoods($cp_id, $target_store_id, $goods_list,$accountinfo);
        if (!empty($checkData['err_msg'])) {
            return response()->json(['code' => '001', 'msg' => '商品数据调拨失败,' . implode(',', $checkData['err_msg'])]);
        }
        $allot_info_data = $checkData['data'];

        $goods_sn = array_column($allot_info_data,'goods_sn_code');
        $stockList =GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id,'is_del'=>1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->get()
            ->pluck(null,'goods_sn_code')
            ->toArray();

        $categoryIds = array_column($stockList, 'goods_category_id');

        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('id', $categoryIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {

            $order_sncode = StoreCommon::createOrderSn();
            $goods_count = 0;
            foreach ($allot_info_data as $v) {
                $goods_count += $v['count_new'];
            }

            $allot_data = [
                'cp_id' => $cp_id,
                'start_store_id' => $start_store_id,
                'target_store_id' => $target_store_id,
                'order_sncode' => $order_sncode,
                'goods_count' => $goods_count,
                'create_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
            ];

            //调拨单
            $allot_id = GoodsAllot::query()->create($allot_data)->id;

            //调拨明细
            $allotArr=[];
            if ($allot_info_data) {
                foreach ($allot_info_data as $k => $v) {
                    if ($v['count_new'] > $v['count']) {
                        return response()->json(['code' => '001', 'msg' => '商品调拨数量不能大于库存数量！']);
                    }

                    // 追加
                    $v['order_sncode'] = $order_sncode;
                    $v['cp_id'] = $cp_id;
                    $v['start_store_id'] = $start_store_id;
                    $v['target_store_id'] = $target_store_id;
                    $v['p_id'] = $allot_id;
                    $v['create_account_id'] = $accountinfo['id'];
                    $v['create_account_real_name'] = $accountinfo['real_name'];
                    $v['create_at'] = time();

                    $is_gram = $v['goods_category']['is_gram']??0;

                    // 一码多货的商品只有数量和总重量
                    if ($v['is_code_more'] == 2) {
                        $total_netglod_weight = $v['total_netglod_weight'];
                        $total_piece_weight = 0;
                    } else {
                        $total_piece_weight = $v['piece_weight'] > 0 ? ($v['piece_weight'] * $v['count_new']) : 0;
                        $total_netglod_weight = $v['netglod_weight'] > 0 ? ($v['netglod_weight'] * $v['count_new']) : 0;
                    }

                    $v['total_piece_weight'] = $total_piece_weight;
                    $v['total_netglod_weight'] = $total_netglod_weight;
                    $goods=$v;
                    $goods['count'] = $v['count_new'];
                    $goods['total_piece_weight'] = $total_piece_weight;
                    $goods['total_netglod_weight'] = $total_netglod_weight;

                    unset($v['id'], $v['allot_count'], $v['goods_brand'], $v['goods_category'], $v['goods_craft'], $v['goods_pricetype'], $v['goods_stone'], $v['goods_style'], $v['odds'], $v['paytype_info'], $v['pricetype'], $v['sales_count'], $v['start_stockin_store_id'], $v['startstoreinfo'], $v['storeinfo'], $v['supply'], $v['store_id'], $v['goods_content'], $v['goods_content_id'], $v['electronic_scale'],$v['repllennish_costglod_price']);

                    $stock =$stockList[$v['goods_sn_code']]?? [];
                   // $is_gram =$category[$stock['goods_category_id']]['is_gram']??0;
                    if(empty($stock)){
                        return response()->json(['code' => '001', 'msg' => '调拨的商品不存在']);
                    }

                    list($deduct_total_cost_fee,$remaining_cost_fee) =(new Goods())->deductTotalCost($stock,$goods);
                    $v['total_cost_fee'] =$deduct_total_cost_fee;
                    $allotArr[] =$v;
                    $total_cost_fee =$remaining_cost_fee;

                    $stock['count'] =$stock['count']-$v['count_new'];
                    $stock['allot_count'] =$stock['allot_count']+$v['count_new'];
                    $stock['total_piece_weight'] =$stock['total_piece_weight']-$total_piece_weight;
                    $stock['total_netglod_weight'] =$stock['total_netglod_weight']-$total_netglod_weight;

                    GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $start_store_id, 'goods_sn_code' => $v['goods_sn_code'],'is_del'=>1])->update([
                        'count' => $stock['count'],
                        'allot_count' => $stock['allot_count'],
                        'total_piece_weight' => $stock['total_piece_weight'],
                        'total_netglod_weight' => $stock['total_netglod_weight'],
                        'total_cost_fee' => $total_cost_fee
                    ]);

                    // GoodsLogType 12调拨出库
                    Goods::goodsLog($request, 0, $target_store_id, $v, $v['count_new'], 12, $order_sncode);

                }
            }

            GoodsAllotInfolist::query()->insert($allotArr);

            DB::commit();

            return response()->json(['code' => '000', 'msg' => '添加成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            info('调拨失败'.$e->getFile().$e->getLine().$e->getMessage());
            return response()->json(['code' => '001', 'msg' => '添加失败']);
        }
    }

    /**
     * 调拨编辑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'goods_list']);
        $Validate = new ValidateGoodsGoodsAllot('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $allot_one = GoodsAllot::query()->where(['id'=>$req_data['id'],'is_del'=>1])->first();
        if (!$allot_one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $allot_one = $allot_one->toArray();
        if ($allot_one['audit_status'] != 1) {
            return response()->json(['code' => '001', 'msg' => '订单不能被编辑']);
        }

        $goods_list = $req_data['goods_list'];
        $goods_list = is_array($goods_list) ? $goods_list : (is_array(json_decode($goods_list, true)) ? json_decode($goods_list, true) : []);
        // 检查商品调拨数据
        $checkData =(new GoodsAllotService())->checkAllotGoods($cp_id, $allot_one['target_store_id'], $goods_list,$accountinfo);
        if (!empty($checkData['err_msg'])) {
            return response()->json(['code' => '001', 'msg' => '商品数据调拨失败,' . implode(',', $checkData['err_msg'])]);
        }

        $allot_info_data = $checkData['data'];
        $start_store_id = (int)$accountinfo['store_ids'];
        $goods_count = array_sum(array_column($allot_info_data, 'count_new')) ?? 0;
        // 查询历史调拨
        $old_allot_list = GoodsAllotInfolist::query()->where(['p_id' => $req_data['id'], 'is_del' => 1])->get()->toArray();

        $goods_sn_arr = array_column($allot_info_data,'goods_sn_code');
        $stockList =GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id,'is_del'=>1])
            ->whereIn('goods_sn_code', $goods_sn_arr)
            ->get()
            ->pluck(null,'goods_sn_code')
            ->toArray();

        $categoryIds = array_column($stockList, 'goods_category_id');

        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('id', $categoryIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {

            GoodsAllot::where('id', $req_data['id'])->update([
                'goods_count' => $goods_count,
                'update_at' => time(),
            ]);

            // 先把所有的还回去
            if (!empty($old_allot_list)) {
                foreach ($old_allot_list as $v) {

                    $stock =$stockList[$v['goods_sn_code']]?? [];
                    $is_gram =$category[$stock['goods_category_id']]['is_gram']??0;
                    if(empty($stock)){
                        return response()->json(['code' => '001', 'msg' => '调拨的商品不存在']);
                    }

                    list($total_cost_fee,$costglod_price,$piececost_fee)=(new Goods())->incrTotalCost($stock,$v,$is_gram);

                    $count =$stock['count']+$v['count_new'];
                    $allot_count =$stock['allot_count']-$v['count_new'];
                    $total_piece_weight =$stock['total_piece_weight']+$v['total_piece_weight'];
                    $total_netglod_weight =$stock['total_netglod_weight']+$v['total_netglod_weight'];
                    $stock['count'] =$count;
                    $stock['total_piece_weight'] =$total_piece_weight;
                    $stock['total_netglod_weight'] =$total_netglod_weight;

                    GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $start_store_id, 'goods_sn_code' => $v['goods_sn_code'],'is_del'=>1])->update([
                        'count' => $count,
                        'allot_count' => $allot_count,
                        'total_piece_weight' =>$total_piece_weight,
                        'total_netglod_weight' => $total_netglod_weight,
                        'total_cost_fee' => $total_cost_fee,
                        'costglod_price'=>$costglod_price,
                        'piececost_fee'=>$piececost_fee
                    ]);
                }
                GoodsAllotInfolist::where('p_id', $req_data['id'])->update([
                    'is_del' => 2,
                    'update_at' => time(),
                ]);
            }

            // 因为之前还回商品库存，此处需要重新查询商品库存
            $newStockList =GoodsStockList::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id,'is_del'=>1])
                ->whereIn('goods_sn_code', $goods_sn_arr)
                ->get()
                ->pluck(null,'goods_sn_code')
                ->toArray();
            // 重新写入调拨数据
            $allotArr=[];
            if (!empty($allot_info_data)) {
                foreach ($allot_info_data as $v) {
                    if ($v['count_new'] > $v['count']) {
                        return response()->json(['code' => '001', 'msg' => '商品调拨数量不能大于库存数量！']);
                    }

                    // 追加
                    $v['cp_id'] = $cp_id;
                    $v['start_store_id'] = $start_store_id;
                    $v['p_id'] = $req_data['id'];
                    $v['update_account_id'] = $accountinfo['id'];
                    $v['update_account_real_name'] = $accountinfo['real_name'];
                    $v['update_at'] = time();

                    // 一码多货的商品只有数量和总重量
                    if ((int)$v['is_code_more'] === 2) {
                        $total_netglod_weight = $v['total_netglod_weight'];
                        $total_piece_weight = 0;
                    } else {
                        $total_piece_weight = $v['piece_weight'] > 0 ? ($v['piece_weight'] * $v['count_new']) : 0;
                        $total_netglod_weight = $v['netglod_weight'] > 0 ? ($v['netglod_weight'] * $v['count_new']) : 0;
                    }

                    $v['total_piece_weight'] = $total_piece_weight;
                    $v['total_netglod_weight'] = $total_netglod_weight;
                    $is_gram =$v['goods_category']['is_gram']??0;

                    $goods= $v;
                    $goods['count']= $v['count_new'];
                    $goods['total_piece_weight']=$total_piece_weight;
                    $goods['total_netglod_weight']=$total_netglod_weight;

                    // 删除无效数据
                    unset($v['id'],
                        $v['electronic_scale'],
                        $v['goods_brand'],
                        $v['goods_category'],
                        $v['goods_content'],
                        $v['goods_content_id'],
                        $v['goods_craft'],
                        $v['goods_pricetype'],
                        $v['goods_stone'],
                        $v['goods_style'],
                        $v['paytype_info'],
                        $v['sales_count'],
                        $v['start_stockin_store_id'],
                        $v['startstoreinfo'],
                        $v['storeinfo'],
                        $v['store_id'],
                        $v['supply'],
                    );



                    $newStock =$newStockList[$v['goods_sn_code']]?? [];
                    //$is_gram =$category[$stock['goods_category_id']]['is_gram']??0;
                    if(empty($stock)){
                        return response()->json(['code' => '001', 'msg' => '调拨的商品不存在']);
                    }

                    list($deduct_total_cost_fee,$remaining_cost_fee) =(new Goods())->deductTotalCost($newStock,$goods);
                    $v['total_cost_fee']=$deduct_total_cost_fee;
                    $allotArr[] =$v;
                    $count =$newStock['count']-$v['count_new'];
                    $allot_count =$newStock['allot_count']+$v['count_new'];
                    $total_piece_weight =$newStock['total_piece_weight']-$v['total_piece_weight'];
                    $total_netglod_weight =$newStock['total_netglod_weight']-$v['total_netglod_weight'];
                    $newStock['count']=$count;
                    $newStock['total_piece_weight']=$total_piece_weight;
                    $newStock['total_netglod_weight']=$total_netglod_weight;

                    $total_cost_fee =$remaining_cost_fee;
                    GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $start_store_id, 'goods_sn_code' => $v['goods_sn_code'],'is_del'=>1])->update([
                        'count' => $count,
                        'allot_count' => $allot_count,
                        'total_piece_weight' =>$total_piece_weight,
                        'total_netglod_weight' => $total_netglod_weight,
                        'total_cost_fee' => $total_cost_fee
                    ]);
                }
                GoodsAllotInfolist::query()->insert($allotArr);
            }

            DB::commit();

            return response()->json(['code' => '000', 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '编辑失败' . $e->getMessage()]);
        }

    }

    /**
     * 删除
     */
    public function dopostdel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateGoodsGoodsAllot('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        DB::beginTransaction();
        try {
            GoodsAllot::where('id', $req_data['id'])->update([
                'is_del' => 2,
                'update_at' => time(),
            ]);

            GoodsAllotInfolist::where('p_id', $req_data['id'])->update([
                'is_del' => 2,
                'update_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '001', 'msg' => '删除成功']);
    }

    /**
     * 导入
     * 只导入一个单子
     */
    public function doimport(Request $request)
    {
        $req_data = $request->only(['target_store_id', 'supply_id']);
        $Validate = new ValidateGoodsGoodsAllot('import');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $data = [];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
        }
        if(empty($data)){
            return response()->json(['code' => '001', 'msg' => '导入的数据不存在']);
        }

        $return_msg = [];

        $target_store_id = $req_data['target_store_id'];
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = (int)$accountinfo['store_ids'];

        $goods_sn_codes = array_column($data, 0);
        $goodsList = GoodsStockList::query()->where('cp_id', $cp_id)->where('is_del',1)
            ->whereIn('goods_sn_code', $goods_sn_codes)
            ->get()
            ->pluck(null, 'goods_sn_code')
            ->toArray();

        $allotArr = [];
        foreach ($data as $key => $val) {
            //表头跳过
            if ($key == 0) {
                continue;
            }
            if (empty($val)) {
                $return_msg[] = '导入失败，第【' . $key . '】行条码为空';
                continue;
            }

            $goods = $goodsList[trim($val[0])] ?? [];
            if (!empty($goods)) {
                if ($val[1] === '否') {
                    $is_code_more = 1;
                } else {
                    $is_code_more = 2;
                }
                if ($goods['is_code_more'] != $is_code_more) {
                    $return_msg[] = '导入失败，条码【' . $key . '】，一码多货状态和库存不一致。';
                    continue;
                }

                // 追加
                $goods['cp_id'] = $cp_id;
                $goods['start_store_id'] = $start_store_id;
                $goods['target_store_id'] = $target_store_id;

                $goods['count_new'] = trim($val[2]);
                if ($val[1] === '否') {
                    $goods['total_piece_weight'] = $goods['count_new'] * $goods['piece_weight'];
                    $goods['total_netglod_weight'] = $goods['count_new'] * $goods['netglod_weight'];
                } else {
                    $goods['total_piece_weight'] = empty($val[3]) ? 0 : (int)$val[3];
                    $goods['total_netglod_weight'] = empty($val[4]) ? 0 : (int)$val[4];
                    if (empty($goods['total_netglod_weight'])) {
                        return response()->json(['code' => '001', 'msg' => '导入失败，条码【' . $key . '】，一码多货商品总金重必填']);
                    }
                }
                $goods['create_account_id'] = $accountinfo['id'];
                $goods['create_account_real_name'] = $accountinfo['real_name'];
                $goods['create_at'] = time();

                // 删除不需要的参数
                unset($goods['store_id'], $goods['allot_count'], $goods['start_stockin_store_id'], $goods['create_at'], $goods['del_at'], $goods['pricetype'], $goods['odds']);
                $allotArr[] = $goods;
            } else {
                $return_msg[] = '导入失败，条码【' . $key . '】，商品不存在';
            }
        }

        if (!empty($return_msg)) {
            return response()->json(['code' => '001', 'msg' => '添加失败' . implode(',', $return_msg)]);
        }

        $checkData =(new GoodsAllotService())->checkAllotGoods($cp_id,$target_store_id,$allotArr,$accountinfo);

        if (!empty($checkData['err_msg'])) {
            return response()->json(['code' => '001', 'msg' => '商品数据调拨失败,' . implode(',', $checkData['err_msg'])]);
        }

        $allotArr = $checkData['data'];

        $goods_sn = array_column($allotArr,'goods_sn_code');
        $stockList =GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id,'is_del'=>1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->get()
            ->pluck(null,'goods_sn_code')
            ->toArray();

        $categoryIds = array_column($stockList, 'goods_category_id');

        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1,'store_id' => $start_store_id])
            ->whereIn('id', $categoryIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {
            $order_sncode = StoreCommon::createOrderSn();
            $allot_data = [
                'cp_id' => $cp_id,
                'start_store_id' => $start_store_id,
                'target_store_id' => $target_store_id,
                'order_sncode' =>$order_sncode,
                'supply_id' => $req_data['supply_id'],
                'create_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
            ];

            //调拨单
            $allot_id = GoodsAllot::create($allot_data)->id;
            foreach ($allotArr as $goods) {
                $goods['p_id'] = $allot_id;
                // 扣减商品库存

                $stock =$stockList[$goods['goods_sn_code']]?? [];
                $is_gram =$category[$goods['goods_category_id']]['is_gram']??0;
                if(empty($stock)){
                    return response()->json(['code' => '001', 'msg' => '调拨的商品不存在']);
                }

                list($deduct_total_cost_fee,$remaining_cost_fee)=(new Goods())->deductTotalCost($stock,$goods);
                $count =$stock['count']-$goods['count_new'];
                $allot_count =$stock['allot_count']+$goods['count_new'];
                $total_piece_weight =$stock['total_piece_weight']-$goods['total_piece_weight'];
                $total_netglod_weight =$stock['total_netglod_weight']-$goods['total_netglod_weight'];


                //$stock['count']=$count;
                //$stock['total_piece_weight']=$total_piece_weight;
                //$stock['total_netglod_weight']=$total_netglod_weight;
                //$total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$is_gram);
                GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $start_store_id, 'goods_sn_code' => $goods['goods_sn_code'],'is_del'=>1])->update([
                    'count' => $count,
                    'allot_count' => $allot_count,
                    'total_piece_weight' =>$total_piece_weight,
                    'total_netglod_weight' => $total_netglod_weight,
                    'total_cost_fee' => $remaining_cost_fee
                ]);

                // 调拨单的总成本
                $goods['count_new'] =(int)$goods['count_new'];
                $goods['total_cost_fee'] =$deduct_total_cost_fee;

                GoodsAllotInfolist::query()->create($goods);
                // GoodsLogType 12调拨出库
                Goods::goodsLog($request, 0, $target_store_id, $goods, $goods['count'], 12, $order_sncode);
            }

            DB::commit();
            return response()->json(['code' => '000', 'msg' => '添加成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }


    }

    /**
     * 模板下载
     */
    public function dotemplate()
    {
        $row = [[
            'store_name' => '条码',
            'is_code_more' => '是否一码多货',
            'real_name' => '补货数',
            'total_piece_weight' => '总件重',
            'total_netglod_weight' => '总金重',
        ]];

        $options = [
            'B' => ['否', '是']
        ];

        $datawith = [
            'A' => '25', 'B' => '25', 'C' => '25', 'D' => '25', 'E' => '25'
        ];

        $filename = '商品补货导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $id = $request['id'] ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $type = $request->type ?? 3;
        $ids = $request['ids'];

        $where = [];
        $order_sncode = $request->order_sncode;
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_style_id = (int)$request->goods_style_id;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = (int)$request->goods_category_id;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = (int)$request->audit_status;
        if ($audit_status > 0) {
            $where[] = ['audit_status', $audit_status];
        }

        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if ($type == 1) {
            $query = GoodsAllotInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_category_id', $ids);
            }

            $list = $query->groupBy('goods_category_id')
                ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new'))
                ->get()->toArray();

            $row = [
                ['table_header' => '商品调拨-调拨汇总'],
                [
                    'audit_status' => '状态',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'goods_style' => '款式',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count_new'] ? '审核' : '审核中'),
                    'category_name' => $val['goods_category']['category_name'],
                    'category_name1' => $val['goods_category']['category_name'],
                    'goods_style' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                ];
            }
        } elseif ($type == 2) {
            $query = GoodsAllotInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_style_id', $ids);
            }

            $list = $query->groupBy('goods_style_id')
                ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new'))
                ->get()->toArray();

            $row = [

                ['table_header' => '商品调拨-按款式汇总'],
                [
                    'audit_status' => '状态',
                    'goods_style' => '款式',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count_new'] ? '审核' : '审核中'),
                    'goods_style' => $val['goods_style'] ? $val['goods_style']['style_name'] : '--',
                    'category_name' => '--',
                    'category_name1' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                ];
            }
        } elseif ($type == 3) {
            // 明细导出
            $row = [

                ['table_header' => '商品调拨-调拨明细'],
                [
                    'start_store' => '起始门店',
                    'target_store' => '目的门店',
                    'goods_brand_name' => '品牌',
                    'category_name' => '入库类别',
                    'category_name_2' => '商品类别',
                    'goods_img' => '商品图片',
                    'goods_sn_code' => '条码',
                    'goods_name' => '品名',
                    'style_name' => '款式',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签售价',
                    'piece_weight' => '入库重量',
                    'piece_weight_new' => '重量',
                    'netglod_weight' => '入库金重',
                    'netglod_weight_new' => '金重',
                    'total_piece_weight' => '入库总重量', //piece_weight*count
                    'total_piece_weight_new' => '总重量', //piece_weight_new*count
                    'gramprice_fee' => '克销工费',
                    'pieceprice_fee' => '件销工费',
                    'costglod_price' => '金价',
                    'costpiece_fee' => '件成本工费',
                    'costgram_fee' => '克成本工费',
                    'total_fee' => '总成本',
                    'content' => '含量',
                    'count' => '库存数量',
                    'count_new' => '调拨数量',
                    'allot_count' => '调拨数量',
                    'cf_no' => '证书号',
                    'cf_no_gia' => 'GIA证书号',
                    'main_stone_weigth' => '主石重',
                    'main_stone_count' => '主石数',
                    'main_stone_val' => '主石值',
                    'other_stone_weigth' => '副石重',
                    'other_stone_count' => '副石数',
                    'other_stone_val' => '副石值',
                    'color' => '颜色',
                    'clarity' => '净度',
                    'cut' => '切工',
                ]];

            $list = GoodsAllotInfolist::getExportList($request)['list'];


            $is_store_account = StoreCommon::getIsStoreAccount($request);
            if (!$is_store_account) {
                unset($row[1]['supply_name']);
                unset($row[1]['paymoney']);
                unset($row[1]['costglod_price']);
                unset($row[1]['total_fee']);
                unset($row[1]['piececost_fee']);
                unset($row[1]['piececost_fee_total']);
            }

            $exceldata = [];
            foreach ($list as $val) {
                $is_gram =$val['goods_category']['is_gram']??0;
                $exceldata[] = [
                    'start_store' => $val['startstoreinfo']['store_name'] ?? '',
                    'target_store' => $val['targetstoreinfo']['store_name'] ?? '',
                    'goods_brand_name' => $val['brand']['brand_name'] ?? '',
                    'category_name' => $val['goods_category']['category_name'] ?? '',
                    'category_name_2' => $val['goods_category']['category_name'] ?? '',
                    'goods_img' => $val['goods_img'],
                    'goods_sn_code' => $val['goods_sn_code'],
                    'goods_name' => $val['goods_name'],
                    'style_name' => $val['goods_style']['style_name'] ?? '',
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'piece_weight' => $val['piece_weight'],
                    'piece_weight_new' => $val['piece_weight_new'],
                    'netglod_weight' => $val['netglod_weight'],
                    'netglod_weight_new' => $val['netglod_weight_new'],
                    'total_piece_weight' => $is_gram==1?($val['total_netglod_weight'] ?? 0):($val['total_piece_weight'] ?? 0),
                    'total_piece_weight_new' =>  $is_gram==1?($val['total_netglod_weight_new'] ?? 0):($val['total_piece_weight_new'] ?? 0),
                    'gramprice_fee' => $val['gramprice_fee'] / 100,
                    'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                    'costglod_price' => $val['costglod_price'] / 100,
                    'costpiece_fee' => $val['costpiece_fee'] / 100,
                    'costgram_fee' => $val['costgram_fee'] / 100,
                    'total_fee' => '总成本',
                    'content' => $val['content'],
                    'count' => $val['count'],
                    'count_new' => $val['count_new'],
                    'allot_count' => $val['allot_count'],
                    'cf_no' => $val['cf_no'],
                    'cf_no_gia' => $val['cf_no_gia'],
                    'main_stone_weigth' => $val['main_stone_weigth'],
                    'main_stone_count' => $val['main_stone_count'],
                    'main_stone_val' => $val['main_stone_val'],
                    'other_stone_weigth' => $val['other_stone_weigth'],
                    'other_stone_count' => $val['other_stone_count'],
                    'other_stone_val' => $val['other_stone_val'],
                    'color' => $val['color'],
                    'clarity' => $val['clarity'],
                    'cut' => $val['cut'],
                ];
            }

        } else {
            // 商品调拨列表导出
            $row = [
                ['table_header' => '商品调拨'],
                [
                    'start_store' => '起始门店',
                    'target_store' => '目的门店',
                    'order_sncode' => '订单号',
                    'audit_status' => '订单状态',
                    'goods_count' => '商品量',
                    'review_num' => '审核数',
                    'reject_num"' => '取消数',
                    'create_account_real_name' => '创建人',
                    'create_at' => '库存时间',
                    'total_paymoney' => '应付款',
                    'remark' => '备注',
                ]];
            $request['isgetall'] = 1;
            $list = GoodsAllot::getList($request)['list'] ?? [];

            $ids = array_column($list, 'id');

            $goods_count = GoodsAllotInfolist::query()
                ->where('is_del',1)
                ->whereIn('p_id', $ids)
                ->selectRaw('p_id,SUM(count_new) as count_new')
                ->groupBy('p_id')
                ->pluck('count_new', 'p_id')
                ->toArray();

            $review_num = GoodsAllotInfolist::query()
                ->where('is_del',1)
                ->where('audit_status', 2)
                ->whereIn('p_id', $ids)
                ->selectRaw('p_id,SUM(count_new) as count_new')
                ->groupBy('p_id')
                ->pluck('count_new', 'p_id')
                ->toArray();

            $reject_num = GoodsAllotInfolist::query()
                ->where('is_del',1)
                ->where('audit_status', 3)
                ->whereIn('p_id', $ids)
                ->selectRaw('p_id,SUM(count_new) as count_new')
                ->groupBy('p_id')
                ->pluck('count_new', 'p_id')
                ->toArray();

            $paymoney = GoodsAllotInfolist::query()
                ->where('is_del',1)
                ->whereIn('p_id', $ids)
                ->selectRaw('p_id,SUM(paymoney) as paymoney')
                ->groupBy('p_id')
                ->pluck('paymoney', 'p_id')
                ->toArray();
            $exceldata = [];
            foreach ($list as $item) {
                $exceldata[] = [
                    'start_store' => $item['startstoreinfo']['store_name'] ?? '',
                    'target_store' => $item['targetstoreinfo']['store_name'] ?? '',
                    'order_sncode' => $item['order_sncode'] ?? '',
                    'audit_status' => $item['audit_status'] == 1 ? '待审核' : ($item['audit_status'] == 2 ? '审核中' : '审核'),
                    'goods_count' => $goods_count[$item['id']] ?? 0,
                    'review_num' => $review_num[$item['id']] ?? 0,
                    'reject_num' => $reject_num[$item['id']] ?? 0,
                    'create_account_real_name' => $item['create_account_real_name'],
                    'total_paymoney' => ($paymoney[$item['id']] ?? 0) / 100,
                    'remark' => $item['remark'],

                ];
            }
        }

        $filename = '商品调拨信息导出_' . time() . '.xlsx';

        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 列表
     * 目的门店、供应商、订单状态【未审核、审核中、已审核】
     */
    public function getlist(Request $request)
    {
        $list = GoodsAllot::getList($request);

        //统计明细中商品数、审核数、驳回数、应付账款
        if ($list) {
            foreach ($list['list'] as &$val) {
                $val['goods_count'] = GoodsAllotInfolist::where(['p_id' => $val['id'],'is_del'=>1])->sum('count_new');
                //审核成功
                $val['review_num'] = GoodsAllotInfolist::where(['p_id' => $val['id'], 'audit_status' => 2,'is_del'=>1])->sum('count_new');
                //审核取消
                $val['reject_num'] = GoodsAllotInfolist::where(['p_id' => $val['id'], 'audit_status' => 3,'is_del'=>1])->sum('count_new');
                //应付账款
                $val['total_paymoney'] = GoodsAllotInfolist::where(['p_id' => $val['id'],'is_del'=>1])->sum('paymoney');
            }
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $one = GoodsAllot::getOne($request);
        if ($one) $one = $one->toArray();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $one]);
    }

    /**
     * 查看明细
     */
    public function getinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsAllot::with(['startstoreinfo', 'targetstoreinfo'])->where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where[] = ['is_del',1];
        $goods_sn_code = $request->order_sncode ?? '';
        if ($goods_sn_code != '') {
            $where[] = ['goods_sn_code', 'like', '%' . $goods_sn_code . '%'];
        }

        $goods_style_id = $request->goods_style_id ?? 0;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = $request->audit_status ?? 0;

        //按照类别汇总
        $list1_new = $list2_new = [];
        $list1 = GoodsAllotInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list1) {
            foreach ($list1 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count_new']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count_new']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1_new = array_values($list1);
        }

        //按照款式汇总
        $list2 = GoodsAllotInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_style_id')
            ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list2) {
            foreach ($list2 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count_new']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count_new']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list2[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list2[$k]);
                    }
                }
            }
            $list2_new = array_values($list2);
        }

        //查询子订单详情
        $list3_query = GoodsAllotInfolist::with(['goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'brand'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);
        if ($audit_status > 0) {
            $list3_query->where('audit_status', $audit_status);
        }
        $list3 = $list3_query->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1_new, 'list2' => $list2_new, 'list3' => $list3]]);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        // 待操作的明细
        if (count($goods_category_ids) > 0) {
            $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        $allot = GoodsAllot::query()
            ->where(['cp_id' => $cp_id,'is_del'=>1])
            ->where('id', $p_id)
            ->first();

        if (empty($infolist) || empty($allot)) {
            return response()->json(['code' => '001', 'msg' => '暂无审核数据']);
        }
        $allot = $allot->toArray();

        if ($store_id>0&&$allot['target_store_id'] != $store_id) {
            return response()->json(['code' => '001', 'msg' => '只有目的门店店长和管理员才能审核']);
        }


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                GoodsAllotInfolist::where(['id' => $id, 'cp_id' => $cp_id,'is_del'=>1])->update(['audit_status' => 2, 'audit_success_count' => $info['count_new'], 'audit_at' => time()]);

                $where['cp_id'] = $cp_id;
                $where['store_id'] = $info['target_store_id'];
                $where['goods_sn_code'] = $info['goods_sn_code'];
                $where['is_del'] =1;
                $stock = GoodsStockList::query()
                    ->where($where)
                    ->first();
                $total_netglod_weight = $info['total_netglod_weight'];
                $total_piece_weight = $info['total_piece_weight'];
                if (!empty($stock)) {
                    $stock=$stock->toArray();
                    $category = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'id' => $info['goods_category_id']])->first();
                    $category = empty($category) ? [] : $category->toArray();


                    $is_gram =$category['is_gram']??0;
                    list($total_cost_fee,$costglod_price,$piececost_fee)=(new Goods())->incrTotalCost($stock,$info,$is_gram);
                    $count =$stock['count']+$info['count_new'];
                    $total_piece_weight =$stock['total_piece_weight']+$total_piece_weight;
                    $total_netglod_weight =$stock['total_netglod_weight']+$total_netglod_weight;

                   // $stock['count'] =$count;
                   // $stock['total_piece_weight'] =$total_piece_weight;
                   // $stock['total_netglod_weight'] =$total_netglod_weight;

                   // $total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$is_gram);
                    // 计算总成本
                    GoodsStockList::query()
                        ->where($where)
                        ->update([
                            'count' =>$count,
                            'total_netglod_weight' => $total_netglod_weight,
                            'total_piece_weight' => $total_piece_weight,
                            'total_cost_fee'=>$total_cost_fee,
                            'costglod_price'=>$costglod_price,
                            'piececost_fee'=>$piececost_fee

                        ]);
                } else {
                    $goods = GoodsStockList::query()
                        ->where('cp_id', $cp_id)
                        ->where('is_del', 1)
                        ->where('store_id', $info['start_store_id'])
                        ->where('goods_sn_code', $info['goods_sn_code'])
                        ->first();
                    $category = GoodsCategory::query()->where(['cp_id' => $cp_id, 'is_del' => 1, 'id' => $goods['goods_category_id']])->first();

                    $goods = empty($goods) ? [] : $goods->toArray();
                    $category = empty($category) ? [] : $category->toArray();
                    unset($goods['id']);
                    // 需要覆盖的参数必须使用调拨过来的参数
                    $goods['count'] = $info['count_new'];
                    $goods['store_id'] = $info['target_store_id'];
                    $goods['order_sncode'] = StoreCommon::createOrderSn();
                    $goods['cp_id'] = $cp_id;
                    $goods['start_store_id'] = $info['start_store_id'];
                    $goods['start_category'] = $category;
                    $goods['total_netglod_weight'] = $total_netglod_weight;
                    $goods['total_piece_weight'] = $total_piece_weight;
                    $goods['allot_count'] = 0;
                    $goods['sales_count'] = 0;

                    $res = $this->checkGoodsStock($goods);

                    if ($res === false) {
                        return response()->json(['code' => '001', 'msg' => '调拨失败']);
                    }
                }

                // 明细审核状态
                $audit_status_count = GoodsAllotInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                // 调拨单审核成功数
                GoodsAllot::where(['id' => $info['p_id'], 'cp_id' => $cp_id,'is_del'=>1])->increment('audit_success_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 11调拨入库
                Goods::goodsLog($request, $info['start_store_id'], $info['target_store_id'], $info, $info['count_new'], 11, $info['order_sncode']);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            info('审核失败'.$e->getFile().$e->getLine().$e->getMessage());
            return response()->json(['code' => '001', 'msg' => '审核失败']);
        }
        return response()->json(['code' => '000', 'msg' => '审核成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (count($goods_category_ids) > 0) {
            $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsAllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('id', $ids)->get()->toArray();
            }
        }


        $goods_sn = array_column($infolist,'goods_sn_code');
        $start_store_id = array_column($infolist,'start_store_id');
        $stockList =GoodsStockList::query()
            ->where(['cp_id' => $cp_id,'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->whereIn('store_id', $start_store_id)
            ->get()
            ->pluck(null,'goods_sn_code')
            ->toArray();

        $categoryIds = array_column($stockList, 'goods_category_id');
        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('id', $categoryIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsAllotInfolist::where(['id' => $id, 'cp_id' => $cp_id,'is_del'=>1])->update(['audit_status' => 3, 'audit_failed_count' => $info['count_new'], 'audit_at' => time()]);
                $audit_status_count = GoodsAllotInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                $stock =$stockList[$info['goods_sn_code']]??[];
                if(empty($stock)){
                    return response()->json(['code' => '001', 'msg' => '商品数据不存在']);
                }

                $is_gram =$category[$stock['goods_category_id']]['is_gram']??0;
                list($total_cost_fee,$costglod_price,$piececost_fee) =(new Goods())->incrTotalCost($stock,$info,$is_gram);
                $count =$stock['count']+$info['count_new'];
                $allot_count =$stock['allot_count']-$info['count_new'];
                $total_piece_weight =$stock['total_piece_weight']+$info['total_piece_weight'];
                $total_netglod_weight =$stock['total_netglod_weight']+$info['total_netglod_weight'];

                //$stock['count'] =$count;
               // $stock['total_piece_weight'] =$total_piece_weight;
                //$stock['total_netglod_weight'] =$total_netglod_weight;

                //$total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$is_gram);

                // 审核取消数
                GoodsAllot::where(['id' => $info['p_id'], 'cp_id' => $cp_id,'is_del'=>1])->increment('audit_failed_count', $info['count_new'], ['audit_status' => $audit_status]);

                GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info['start_store_id'], 'goods_sn_code' => $info['goods_sn_code'],'is_del' => 1])->update([
                    'count' => $count,
                    'allot_count' => $allot_count,
                    'total_piece_weight' =>$total_piece_weight,
                    'total_netglod_weight' => $total_netglod_weight,
                    'total_cost_fee'=>$total_cost_fee,
                    'costglod_price'=>$costglod_price,
                    'piececost_fee'=>$piececost_fee

                ]);
                Goods::goodsLog($request, 0, $info['target_store_id'], $info, $info['count_new'], 13, $info['order_sncode']);

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核取消成功']);
    }

    /**
     * 批量审核
     */
    public function doauditsuccessmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择需要审核的商品']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }

        $maininfocount = GoodsAllot::where(['cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('id', $ids)->count();

        if ($maininfocount != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核商品']);
        }

        $infolist = GoodsAllotInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->whereIn('p_id', $ids)->get()->toArray();

        DB::beginTransaction();


        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsAllotInfolist::query()->where(['id' => $id, 'cp_id' => $cp_id,'is_del'=>1])->update(['audit_status' => 2, 'audit_success_count' => $info['count_new'], 'audit_at' => time()]);

                $where['cp_id'] = $cp_id;
                $where['store_id'] = $info['target_store_id'];
                $where['goods_sn_code'] = $info['goods_sn_code'];
                $where['is_del'] = 1;

                $stock = GoodsStockList::query()
                    ->where($where)
                    ->first();

                $total_netglod_weight = $info['total_netglod_weight'];
                $total_piece_weight = $info['total_piece_weight'];
                if (!empty($stock)) {
                    $stock=$stock->toArray();
                    $category = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'id' => $stock['goods_category_id']])->first();
                    $category = empty($category) ? [] : $category->toArray();
                    $is_gram =$category['is_gram']??0;

                    list($total_cost_fee,$costglod_price,$piececost_fee) =(new Goods())->incrTotalCost($stock,$info,$is_gram);

                    $count =$stock['count']+$info['count_new'];
                    $total_piece_weight =$stock['total_piece_weight']+$total_piece_weight;
                    $total_netglod_weight =$stock['total_netglod_weight']+$total_netglod_weight;

                    //$stock['count'] =$count;
                    //$stock['total_piece_weight'] =$total_piece_weight;
                   // $stock['total_netglod_weight'] =$total_netglod_weight;


                    //$total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$is_gram);
                    GoodsStockList::query()
                        ->where($where)
                        ->update([
                            'count' =>$count,
                            'total_netglod_weight' =>$total_netglod_weight,
                            'total_piece_weight' =>$total_piece_weight,
                            'total_cost_fee'=>$total_cost_fee,
                            'costglod_price'=>$costglod_price,
                            'piececost_fee'=>$piececost_fee

                        ]);
                } else {
                    $goods = GoodsStockList::query()
                        ->where('is_del', 1)
                        ->where('cp_id', $cp_id)
                        ->where('store_id', $info['start_store_id'])
                        ->where('goods_sn_code', $info['goods_sn_code'])
                        ->first();
                    $category = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'id' => $goods['goods_category_id']])->first();

                    $goods = empty($goods) ? [] : $goods->toArray();
                    $category = empty($category) ? [] : $category->toArray();
                    unset($goods['id']);
                    $goods['count'] = $info['count_new'];
                    $goods['store_id'] = $info['target_store_id'];
                    $goods['order_sncode'] = StoreCommon::createOrderSn();
                    $goods['cp_id'] = $cp_id;
                    $goods['start_store_id'] = $info['start_store_id'];
                    $goods['start_category'] = $category;
                    $goods['total_netglod_weight'] = $total_netglod_weight;
                    $goods['total_piece_weight'] = $total_piece_weight;
                    $goods['allot_count'] = 0;
                    $goods['sales_count'] = 0;

                    $res = $this->checkGoodsStock($goods);
                    if ($res === false) {
                        return response()->json(['code' => '001', 'msg' => '调拨失败']);
                    }
                }


                $audit_status_count = GoodsAllotInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                // 调拨单审核成功数
                GoodsAllot::where(['id' => $info['p_id'], 'cp_id' => $cp_id,'is_del'=>1])->increment('audit_success_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 11调拨出库
                Goods::goodsLog($request, $info['start_store_id'], $info['target_store_id'], $info, $info['count_new'], 11, $info['order_sncode']);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            info('商品调拨审核失败'.$e->getFile().$e->getLine().$e->getMessage());
            return response()->json(['code' => '001', 'msg' => '审核失败']);
        }
        return response()->json(['code' => '000', 'msg' => '调拨审审核成功']);
    }

    /**
     * 撤审
     */
    public function doauditcancelmore(Request $request)
    {
        $p_ids = $request->ids;
        $p_ids = is_array($p_ids) ? $p_ids : (is_array(json_decode($p_ids, true)) ? json_decode($p_ids, true) : []);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }

        $maininfo_arr = GoodsAllot::where(['cp_id' => $cp_id,'is_del'=>1])->whereIn('audit_status', [1, 2])->whereIn('id', $p_ids)->count();
        if ($maininfo_arr != count($p_ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $infolist = GoodsAllotInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])
            ->whereIn('p_id', $p_ids)
            ->get()
            ->toArray();


        $goods_sn = array_column($infolist,'goods_sn_code');
        $start_store_id = array_column($infolist,'start_store_id');
        $stockList =GoodsStockList::query()
            ->where(['cp_id' => $cp_id,'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->whereIn('store_id', $start_store_id)
            ->get()
            ->pluck(null,'goods_sn_code')
            ->toArray();

        $categoryIds = array_column($stockList, 'goods_category_id');
        $category = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->whereIn('id', $categoryIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsAllotInfolist::where(['id' => $id, 'cp_id' => $cp_id,'is_del'=>1])
                    ->update(['audit_status' => 3, 'audit_failed_count' => $info['count_new'], 'audit_at' => time()]);
                $audit_status_count = GoodsAllotInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1,'is_del'=>1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                $stock =$stockList[$info['goods_sn_code']]??[];
                if(empty($stock)){
                    return response()->json(['code' => '001', 'msg' => '商品数据不存在']);
                }

                $is_gram =$category[$stock['goods_category_id']]['is_gram']??0;

                list($total_cost_fee,$costglod_price,$piececost_fee) =(new Goods())->incrTotalCost($stock,$info,$is_gram);


                $stock['count'] =$stock['count']+$info['count_new'];
                $stock['allot_count'] =$stock['allot_count']-$info['count_new'];
                $stock['total_piece_weight'] =$stock['total_piece_weight']+$info['total_piece_weight'];
                $stock['total_netglod_weight'] =$stock['total_netglod_weight']+$info['total_netglod_weight'];

               // $total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$is_gram);

                // 审核取消数
                GoodsAllot::where(['id' => $info['p_id'], 'cp_id' => $cp_id,'is_del'=>1])->increment('audit_failed_count', $info['count_new'], ['audit_status' => $audit_status]);

                // GoodsLogType 13取消调拨
                Goods::goodsLog($request, 0, $info['start_store_id'], $info, $info['count_new'], 13, $info['order_sncode']);

                GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info['start_store_id'], 'goods_sn_code' => $info['goods_sn_code'],'is_del' => 1])->update([
                    'count' => $stock['count'],
                    'allot_count' =>  $stock['allot_count'],
                    'total_piece_weight' =>  $stock['total_piece_weight'],
                    'total_netglod_weight' => $stock['total_netglod_weight'],
                    'total_cost_fee'=>$total_cost_fee,
                    'costglod_price'=>$costglod_price,
                    'piececost_fee'=>$piececost_fee

                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '调拨审核取消成功']);
    }

    /**
     * @param $data
     * @return bool
     */
    public function checkGoodsStock($data)
    {
        $start_category = $data['start_category'];

        $start_store_id = $data['start_store_id'];
        unset($data['start_category'], $data['start_store_id']);
        // 查询目标店设置分类属性是否一致
        $targetCate = GoodsCategory::query()
            ->where('is_del', 1)
            ->where('store_id', $data['store_id'])
            ->where('cp_id', $data['cp_id'])
            ->where('category_name', $start_category['category_name'])
            ->where('goods_cabinetgroup_id', $start_category['goods_cabinetgroup_id'])
            ->where('goods_metal_id', $start_category['goods_metal_id'])
            ->where('is_recovery', $start_category['is_recovery'])
            ->where('is_sujin', $start_category['is_sujin'])
            ->where('is_maintenance_price', $start_category['is_maintenance_price'])
            ->first();

        if (empty($targetCate)) {
            return false;
        }
        $targetCate = $targetCate->toArray();

        $data['goods_category_id'] = $targetCate['id'];
        $data['stockin_at'] = $data['stockin_at']??0;
        $data['procure_at'] = $data['stockin_at']??0;
        $data['create_at'] = time();
        $data['start_stockin_store_id'] = $start_store_id;
        $data['total_piece_weight'] = isset($data['total_piece_weight']) ? $data['total_piece_weight'] : 0;
        $data['total_netglod_weight'] = isset($data['total_netglod_weight']) ? $data['total_netglod_weight'] : 0;
        if ($data['is_code_more'] == 2) {
            $data['total_cost_fee'] = bcmul((string)($data['costgram_fee'] + $data['costglod_price']), $data['total_netglod_weight'], 0) + $data['costpiece_fee'] * $data['count'];
        } else {
            $is_gram = GoodsCategory::where(['cp_id' => $data['cp_id'], 'is_del' => 1, 'store_id' => $data['store_id'], 'id' => $data['goods_category_id']])->value('is_gram');
            if ($is_gram == 1) {
                $data['total_cost_fee'] = bcmul((string)($data['costgram_fee'] + $data['costglod_price']), $data['total_netglod_weight'], 0) + $data['costpiece_fee'] * $data['count'];
            } else {
                $data['total_cost_fee'] = $data['piececost_fee'] * $data['count'];
            }
        }
        foreach ($data as $key => $val) {
            if ($val == '' || $val == 0) {
                unset($data[$key]);
            }
        }

        GoodsStockList::query()->create($data)->id;

        return true;
    }
}
